var express = require("express");
var router = express.Router();
var utils = require('../utils/index');
var mysql = require("../connect/index");
var { Settle, SettleData } = require('../models/shop/settle.model');

router.get("/", function (req, res, next) {
    res.send(utils.setSendResult());
});


// 获取信息
router.get("/list", function (req, res, next) {
    const query = req.query;
    Settle.findAll().then(result => {
        res.send(utils.setSendResult(200, "查询成功", result));
    })
});
// 新增信息
router.post("/add", function (req, res, next) {
    const params = req.body;
    var settle = Settle.create(params);
    res.send(utils.setSendResult(200, "添加成功", settle));
});
// 批量新增表 - 执行 sql 语句
router.get("/mock/sql", async (req, res, next) => {
    // 假设有两个表的数据
    const shop_settle = [
        { agentid: '11292883842', money: '200',  remark: '备注'},
        { agentid: '11292883843', money: '1203',  remark: '备注'},
        { agentid: '11292883844', money: '3220',  remark: '备注'},
        { agentid: '11292883845', money: '909',  remark: '备注'},
        { agentid: '11292883846', money: '808',  remark: '备注'},
        { agentid: '11292883847', money: '700',  remark: '备注'}
        // 更多行...
    ];
    const shop_settle_data = [{
        settleid: 1, orderid: 1, money: '200', type: '已发货'
    }, {
        settleid: 2, orderid: 2, money: '200', type: '已发货'
    }, {
        settleid: 3, orderid: 2, money:'200', type: '已发货'
    }, {
        settleid: 4, orderid: 1, money: '200', type: '已发货'
    }, {
        settleid: 5, orderid: 3, money: '200', type: '已发货'
    }, {
        settleid: 6, orderid: 1, money:'200', type: '已发货'
    }]

    try {
        await mysql.sequelize.sync(); // 同步模型到数据库
        // 批量插入数据1
        const insertSettle = await Settle.bulkCreate(shop_settle);
        // 批量插入数据2
        const insertSettleData = await SettleData.bulkCreate(shop_settle_data);
        res.send(utils.setSendResult(200, "批量添加成功", insertSettle, insertSettleData));
    } catch (error) {
        res.send(utils.setSendResult(500,  error));
    }
})
// 修改信息
router.post("/edit", function (req, res, next) {
    const params = req.body;
    if (params['id'] == undefined) return res.send(utils.setSendResult(400, "参数错误", {}));
    var settle = Settle.update(params);
    res.send(utils.setSendResult(200, "修改成功", settle));
});
// 删除信息
router.get("/delete", function (req, res, next) {
    const query = req.query;
    if (query['id'] == undefined) return res.send(utils.setSendResult(400, "参数错误", {}));
    var settle = Settle.destroy({
        where: {
            id: query['id']
        }
    });
    res.send(utils.setSendResult(200, "删除成功", settle));
});

module.exports = router;
